package es.us.lsi.daw.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;

/**
 * Servlet Filter implementation class SessionFilter
 */
public class SessionFilter implements Filter {

	    //~ Instance fields ================================================================================================

	    private String expiredUrl = "/login.do";

	    //~ Methods ========================================================================================================

	    public void afterPropertiesSet() throws Exception {
	        Assert.hasText(expiredUrl, "ExpiredUrl required");
	    }

	    /**
	     * Does nothing. We use IoC container lifecycle services instead.
	     */
	    public void destroy() {}

	    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		        throws IOException, ServletException {
		        Assert.isInstanceOf(HttpServletRequest.class, request, "Can only process HttpServletRequest");
		        Assert.isInstanceOf(HttpServletResponse.class, response, "Can only process HttpServletResponse");

		        HttpServletRequest httpRequest = (HttpServletRequest) request;
		        HttpServletResponse httpResponse = (HttpServletResponse) response;
		        
		    	/*WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(httpRequest.getSession().getServletContext());
				Util util = (Util) wc.getBean("util");
				
				String cookieName = util.obtenerMensaje("cookieName");
				int cookieMaxAge= Integer.parseInt(util.obtenerMensaje("cookieMaxAge").trim());
				String cookiePath= util.obtenerMensaje("cookiePath");
				String paramLocaleName= util.obtenerMensaje("paramLocaleName");
				String localeParam = httpRequest.getParameter(paramLocaleName);
				
				Locale locale = null;
				if (localeParam == null) {
					locale = new Locale("es_ES");
				}else {
					locale = new Locale(localeParam);
				}

				Cookie[] cookies = httpRequest.getCookies();
				int i = 0;
				if(cookies!= null){
					for (; i < cookies.length; i++) {
						if (cookies[i].getName().equals(cookieName)) {
							break;
						}
					}
				}

				if (cookies== null || i == cookies.length){//la cooki no existe, la creo	
					Cookie i18nCookie = new Cookie(cookieName, locale.getLanguage());
					i18nCookie.setPath(cookiePath);
					i18nCookie.setMaxAge(cookieMaxAge);
					httpResponse.addCookie(i18nCookie);
				}else if(localeParam!= null) {
					cookies[i].setValue(locale.getLanguage());
					httpResponse.addCookie(cookies[i]);
				}*/
				
		        HttpSession session = httpRequest.getSession(false);
		        String ruta = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
		        if(!ruta.endsWith(".do")){
		        	chain.doFilter(request, response);
		        }else{
		      
		        if (session == null || session.isNew() || SecurityContextHolder.getContext().getAuthentication() == null)
		        {    
		            String targetUrl = httpRequest.getContextPath() + expiredUrl;
		            httpResponse.sendRedirect(httpResponse.encodeRedirectURL(targetUrl));
		            return;
		        }

			
		        chain.doFilter(request, response);
		        }
		    }

	    /**
	     * Does nothing. We use IoC container lifecycle services instead.
	     *
	     * @param arg0 ignored
	     *
	     * @throws ServletException ignored
	     */
	    public void init(FilterConfig arg0) throws ServletException {}

	    public void setExpiredUrl(String expiredUrl) {
	        this.expiredUrl = expiredUrl;
	    }
	}
